package com.chenhy.server.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.chenhy.server.pojo.Employee;
import com.chenhy.server.pojo.MailConstants;
import com.chenhy.server.pojo.MailLog;
import com.chenhy.server.service.IEmployeeService;
import com.chenhy.server.service.IMailLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
// 邮件定时任务
public class MailTask {

    @Autowired
    private IMailLogService mailLogService;

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    // 10秒执行一次
    @Scheduled(cron = "0/10 * * * * ?")
    public void mailTask(){
        // 获取状态为消息投递中的且重试时间小于当前时间（当前时间超过重试时间）的消息（就是需要再次发送的）
        List<MailLog> list = mailLogService.list(new QueryWrapper<MailLog>().eq("status", 0).lt("try_time", LocalDateTime.now()));
        list.forEach(mailLog -> {
            // 如果重试次数已经大于等于三次
            if (mailLog.getCount() >=3){
                // 更新状态为发送失败（不再重试）
                mailLogService.update(new UpdateWrapper<MailLog>().set("status", 2).eq("msg_id", mailLog.getMsgId()));
                return;
            }
            mailLogService.update(new UpdateWrapper<MailLog>().set("count", mailLog.getCount()+1)
                    .set("update_time", LocalDateTime.now())
                    .set("try_time", LocalDateTime.now().plusMonths(MailConstants.MSG_TIMEOUT))
                    .eq("msg_id", mailLog.getMsgId()));
            // 通过消息发送记录中的员工ID拿到员工的完整信息，为重发做准备
            Employee employee = employeeService.getEmployee(mailLog.getEid()).get(0);
            // 重新发送消息
            rabbitTemplate.convertAndSend(mailLog.getExchange(), mailLog.getRouteKey(), employee, new CorrelationData(mailLog.getMsgId()));

        });
    }

}
